package cn.com.callback

import cn.com.callback.CallBackInvoke
import cn.com.elite.EliteBean
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import cn.com.elite.Util

import java.text.SimpleDateFormat

/**
 *
 * @Title: cn.com.callback-RobotListCallRecordInboundsTask
 * @Description:ngsapitask-sw 系统API接口开发Demo，重点关注业务逻辑部分
 * @Author: yzh
 * @Date 2022/12/1 17:04
 *
 */
class ApiRobotCallRecordInboundTask implements CallBackInvoke {

    private static final Log log = LogFactory.getLog(ApiRobotCallRecordInboundTask.class);

    @Override
    void doCallBack(EliteBean eliteBean, String s, Map map, String s1) {

        String result = "";
        try {
            int pageSize = 20;//初始化每页数据
            int beginPage = 0;//初始化分页起始页
            Date date = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.MINUTE, -30);
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String beginTime = sf.format(calendar.getTime());//初始化开始时间
            String endTime = sf.format(date);//初始化结束时间

            Integer resultNum = 20;// 定义循环初始值


            //获取请求接口URL
            String httpUrl = KHDBConfig.getAPIURL(eliteBean, "listCallRecordInbounds");

            //循环调用接口
            JSONObject jsonObject = new JSONObject();

            while (resultNum >= 20) {
                jsonObject.put("beginPage", beginPage);
                jsonObject.put("pageSize", pageSize);
                jsonObject.put("beginTime", beginTime);
                jsonObject.put("endTime", endTime);
                /*jsonObject.put("beginTime", "2022-12-26 00:00:00");
                jsonObject.put("endTime", "2022-12-31 23:59:59");*/
                log.debug("请求语音小秘报文：" + jsonObject.toString());

                //调用语音小秘接口
                Map<String, String> headMap = new HashMap<String, String>();
                headMap.put("Content-Type", "application/json");
                headMap.put("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjdXN0b20iOnsiaWQiOiI0YjIxMTU4YTM5NTMxMWU4OGE3MTAyNDJhYzExMDAwMiIsInVzZXJfaWQiOiIyIiwidXNlcl9uYW1lIjoiZGVwbG95ZXIiLCJkaXNwbGF5X25hbWUiOiJTWVNURU0iLCJlbWFpbCI6ImFkbWluQGVtb3RpYm90LmNvbSIsInBob25lIjoiIiwidHlwZSI6MCwicm9sZXMiOnsiZ3JvdXBzIjpbXSwiYXBwcyI6W119LCJwcm9kdWN0IjpbXSwic3RhdHVzIjoxLCJlbnRlcnByaXNlIjpudWxsLCJjdXN0b20iOm51bGx9LCJleHAiOjE2Njg1MDA4MjksImlzcyI6InNpbXBsZS1hdXRoIiwibmJmIjoxNjY4NDE0NDI5fQ.XqNTme_NeDBCAscDcl1G5Lemg__43yuNSRDcj2I14H0");
                String doPostResult = Util.doHttpPostUseHead(httpUrl, jsonObject.toString(), "UTF-8", 120000, 0, headMap);
                //解析报文转换为json格式
                JSONObject doResultJson = JSONObject.fromObject(doPostResult);
                //获取返回总数据赋值给循环数
                //json数据转换为java集合
                JSONArray jsonArray = JSONArray.fromObject(doResultJson.data.dataList);
                //存入crm表
                resultNum = jsonArray.size();
                log.debug("resultNum:" + resultNum);
                for (int i = 0; i < resultNum; i++) {
                    JSONObject tempJson = jsonArray.getJSONObject(i);

                    String id = tempJson.getString("id");//id
                    String telNumber = tempJson.getString("telNumber");//电话号码
                    String callId = tempJson.getString("callId");//呼叫id
                    String appId = tempJson.getString("appId");//机器人id
                    String callNumber = tempJson.getString("callNumber");//呼叫频次
                    String workflowId = tempJson.getString("workflowId");//场景id
                    String callStatus = tempJson.getString("callStatus");//呼叫结果
                    String callError = tempJson.getString("callError");//呼叫结果原因
                    String beginTimes = tempJson.getString("beginTime");//开始时间
                    String hangupTime = tempJson.getString("hangupTime");//挂断时间
                    String isHangupedByRemote = tempJson.getString("isHangupedByRemote");//是否由用户挂断
                    String complaintRiskCount = tempJson.getString("complaintRiskCount");//发生投诉风险次数
                    String emotionAlertCount = tempJson.getString("emotionAlertCount");//发生情绪异常次数
                    String chatSeconds = tempJson.getString("chatSeconds");//通话时长
                    String chatRounds = tempJson.getString("chatRounds");//对话轮次
                    String callRuleId = tempJson.getString("callRuleId");//命中的呼叫规则ID
                    String dnis = tempJson.getString("dnis");//被叫号码
                    String emotibotName = tempJson.getString("emotibotName");//机器人名称
                    String workflowName = tempJson.getString("workflowName");//场景名称
                    String province = tempJson.getString("province");//归属地

                    String getRecordSql = "select count(1) con from swg_listCallRecordInbounds where callId = '" + callId + "'";
                    def getRecord = eliteBean.chaxun_sql(getRecordSql, "dataSource");
                    def getRecordList = getRecord[0].getAt("con");
					//定义业务类型 1.报修报漏 2.查费交费 3.业务办理
					Integer businessType = 0;
					//定义留言标识
					Integer leavingMessageFlag = 0;
					//录音文件存储地址
                    if (getRecordList == 0 && tempJson.containsKey("extraData")) {
                        //将获取到的附加数据转换为json对象
                        String extraData = tempJson.getString("extraData");//附加数据
                        JSONObject extraDataJson = JSONObject.fromObject(extraData);
                        //判断附加数据中是否存在sysTag标识
                        if (extraDataJson.containsKey("sysTag")) {
                            //获取附加数据判断报修报漏、查费交费、业务办理的字段
                            String sysTag = extraDataJson.getString("sysTag");
							JSONObject sysTagJson = JSONObject.fromObject(sysTag);
							log.debug("sfcz报修报漏" + sysTagJson.containsKey("报修报漏"));
							log.debug("sfcz查费交费" + sysTagJson.containsKey("查费交费"));
							log.debug("sfcz业务办理" + sysTagJson.containsKey("业务办理"));
                            if (sysTagJson.containsKey("报修报漏")) {
                                businessType = 1;
                            } else if (sysTagJson.containsKey("查费交费")) {
                                businessType = 2;
                            } else if (sysTagJson.containsKey("业务办理")) {
                                businessType = 3;
                            }
							 
							//判断是否为留言
							if (sysTagJson.containsKey("留言")) {
								leavingMessageFlag = 1;
								//获取留言录音文件
								String messageRecordUrl = KHDBConfig.getAPIURL(eliteBean, "downloadWav");
								messageRecordUrl += "" + callId + "";
								log.debug("录音下载url:" + messageRecordUrl);


								String saveFile = callId + "-" + KHUtil.getRandomString(6) + ".mp3";
								boolean downFlag = Util.httpDownLoadFile(messageRecordUrl, saveFile, 120000);

								log.info("文件下载成功！开始上传NGS..." + downFlag);

								result = uploadNGS(eliteBean, saveFile);

								log.debug("上传NGS完成：【" + result + "】");

								Util.deleteFile(saveFile);
							}
                        }

                        String doCRMSql = '''INSERT INTO swg_listCallRecordInbounds (
													rec_guid,
													id,
													telNumber,
													callId,
													callNumber,
													appId,
													workflowId,
													callStatus,
													callError,
													callstarttime,
													hangupTime,
													isHangupedByRemote,
													complaintRiskCount,
													emotionAlertCount,
													chatSeconds,
													chatRounds,
													callRuleId,
													extraData,
													dnis,
													emotibotName,
													workflowName,
													province,
													businessType,
													leavingMessageFlag,
													recordPath,
													createddate,
													createdby 
													)
													VALUES(
														\'''' + UUID.randomUUID().toString().toUpperCase() + '''\',
														\'''' + id + '''\',
														\'''' + telNumber + '''\',
														\'''' + callId + '''\',
														\'''' + callNumber + '''\',
														\'''' + appId + '''\',
														\'''' + workflowId + '''\',
														\'''' + callStatus + '''\',
														\'''' + callError + '''\',
														\'''' + beginTimes + '''\',
														\'''' + hangupTime + '''\',
														\'''' + isHangupedByRemote + '''\',
														\'''' + complaintRiskCount + '''\',
														\'''' + emotionAlertCount + '''\',
														\'''' + chatSeconds + '''\',
														\'''' + chatRounds + '''\',
														\'''' + callRuleId + '''\',
														\'''' + extraData + '''\',
														\'''' + dnis + '''\',
														\'''' + emotibotName + '''\',
														\'''' + workflowName + '''\',
														\'''' + province + '''\',
                                                        \'''' + businessType + '''\',
                                                        \'''' + leavingMessageFlag + '''\',
                                                        \'''' + result + '''\',
														getdate(),
														'ELITE'
													)''';
                        Integer recordListRes = eliteBean.update(doCRMSql, "dataSource");
                        log.debug("本次记入CRM表数据数为：" + recordListRes);

                    }
                }
                if (resultNum < 20) {
                    log.debug("任务执行完成");
                }
                beginPage++;
            }

        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    public static String uploadNGS(EliteBean eliteBean, String srcFileName) {

        String ngsFSToken = Util.getAuthToken(KHDBConfig.getAPIURL(eliteBean, "NGS-FS-authUrl"), "elite.ngs", "Letmein_0308");
        log.debug("获取NGS上次Token：" + ngsFSToken);

        File tempFile = new File(srcFileName.trim());
        String fileName = tempFile.getName();

        String uploadResult = Util.uploadFile(KHDBConfig.getAPIURL(eliteBean, "NGS-FS-upload_url"), srcFileName, "/record", KHUtil.getNameWithoutSuffix(fileName), "", ngsFSToken);
        log.debug("文件上传NGS结果：" + uploadResult);

        JSONObject resultJson = JSONObject.fromObject(uploadResult);

        String code = resultJson.getString("code");
        if (code.equals("1")) {
            return KHDBConfig.getAPIURL(eliteBean, "NGS-FS-Get") + resultJson.getString("value");
        } else {
            return null;
        }
    }
}